#include "StdAfx.h"

void MarketData::Start()
{
	if (requestID != -1) { MessageBox::Show("Market Data already requested"); return; }

	TWSLib::IContract ^ic = owner->Account_()->TwsControl()->createContract();

	ic->symbol = owner->Name();
	ic->exchange = "SMART";
	ic->currency = "USD";
	ic->secType = "STK";
	requestID = owner->Account_()->GetNextFreeID();
	owner->Account_()->TwsControl()->reqMktDataEx(requestID, ic, "", 0);
}

void MarketData::Start(TextBox ^textToUpdate)
{
	if (requestID != -1) { MessageBox::Show("Market Data already requested"); return; }

	TWSLib::IContract ^ic = owner->Account_()->TwsControl()->createContract();

	ic->symbol = owner->Name();
	ic->exchange = "SMART";
	ic->currency = "USD";
	ic->secType = "STK";
	requestID = owner->Account_()->GetNextFreeID();
	owner->Account_()->TwsControl()->reqMktDataEx(requestID, ic, "", 1);
	this->textToUpdate = textToUpdate;
}

MarketData::MarketData(Symbol ^owner)
{
	owner->Account_()->TwsControl()->tickPrice += gcnew AxTWSLib::_DTwsEvents_tickPriceEventHandler(this, &MarketData::getMarketData);
	this->owner = owner;
	requestID = -1;
}

void MarketData::getMarketData(System::Object ^sender, AxTWSLib::_DTwsEvents_tickPriceEvent ^e)
{
	MarketDataTypes whatChanged;

	if (e->id != requestID) return;

	if (textToUpdate != nullptr)
	{
		if (e->tickType == 4) textToUpdate->Text = Convert::ToString( Math::Round((double)e->price, 2) );
		return;
	}

	if (e->tickType == 1) { bid = e->price; whatChanged = MarketDataTypes::Bid; }
	if (e->tickType == 2) { ask = e->price; whatChanged = MarketDataTypes::Ask; }
	if (e->tickType == 4) { last = e->price; whatChanged = MarketDataTypes::Last; }
	if (e->tickType == 6) { high = e->price; whatChanged = MarketDataTypes::High; }
	if (e->tickType == 7) { low = e->price; whatChanged = MarketDataTypes::Low; }
	if (e->tickType == 9) { yesterdayClose = e->price; whatChanged = MarketDataTypes::YesterDayClose; }

	this->NewMarketData(whatChanged, e->price);
}